package com.semeureka.fault.mina.impl;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Component;

import com.semeureka.fault.bean.Group;
import com.semeureka.fault.bean.Rawdata;
import com.semeureka.fault.mina.SessionCache;
import com.semeureka.fault.util.Message;

@Component
public class SessionCacheImpl implements SessionCache {
	private Map<Group, IoSession> sessions = new ConcurrentHashMap<Group, IoSession>();

	@Override
	public boolean contains(Group group) {
		for (Group group0 : sessions.keySet()) {
			if (Arrays.equals(group0.getHostCode(), group.getHostCode())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void put(Group group, IoSession session) {
		sessions.put(group, session);
	}

	@Override
	public IoSession get(Group group) {
		for (Entry<Group, IoSession> entry : sessions.entrySet()) {
			if (Arrays.equals(entry.getKey().getHostCode(), group.getHostCode())) {
				return entry.getValue();
			}
		}
		return null;
	}

	@Override
	public void remove(IoSession session) {
		Iterator<Entry<Group, IoSession>> iterator = sessions.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<Group, IoSession> entry = iterator.next();
			if (entry.getValue().equals(session)) {
				iterator.remove();
			}
		}
	}

	@Override
	public void write(Message... messages) {
		if (messages != null && messages.length > 0) {
			IoSession session = get(messages[0].getGroup());
			if (session != null) {
				Rawdata rawdata = null;
				for (int i = 0; i < messages.length; i++) {
					Message message = messages[i];
					if (message instanceof Rawdata) {
						if (rawdata != null) {
							session.write(rawdata);
							rawdata = null;
						}
						session.write(message);
					} else {
						if (rawdata == null) {
							rawdata = new Rawdata();
							rawdata.setGroup(message.getGroup());
						}
						rawdata.addMessage(message);
					}
				}
				if (rawdata != null) {
					session.write(rawdata);
				}
			}
		}
	}
}
